package Firstdroid.Tutorial.Gps;


import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.telephony.TelephonyManager;


import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.String;
import java.net.URI;
import java.util.Date;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;




public class UseGps extends Activity {
	
	long lastTime = System.currentTimeMillis();
	/* fairness interval */
	long delta = 60000;
	/* central server default address */
	String url = "http://cipsm.hpc.pub.ro:8080/CAPIM-WebApp/rest";
	/* program start flag */
	int start = 0;
	/* log to file flag */
	int logToFile = 0;
	/* Ask Android where we can store our file */
	File directory = Environment.getExternalStorageDirectory();

	
	/* Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {	
		
		super.onCreate(savedInstanceState);
		
		TableLayout layout = null;
		layout = new TableLayout(this);	
		
	    /* Select Server button */
		Button button = new Button(this);
	    button.setText("Central Server");
	    layout.addView(button);
	    button.setOnClickListener(new View.OnClickListener() {
	    	public void onClick(View v) {
	    		final AlertDialog.Builder alert = new AlertDialog.Builder(UseGps.this);
	    		final EditText input = new EditText(UseGps.this);
	    		/* set the default server address */
	    		input.setText(url);
	    		alert.setTitle("Server address:port");
	    		alert.setView(input);
	    		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int whichButton) {
	    				url = input.getText().toString();
	    				Toast.makeText(getApplicationContext(), url, Toast.LENGTH_SHORT).show();
	    			}
	    		});
	    	
	    		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int whichButton) {
	    				dialog.cancel();
	    			}
	    		});
	    		
	    		alert.show();
	    	}
	    });
	    
	    /* Log to file radio button */
	    RadioButton rbutton = new RadioButton(this);
	    rbutton.setText("Log to File");
	    layout.addView(rbutton);
	    rbutton.setOnClickListener(new View.OnClickListener() {
	    	public void onClick(View v) {
	    		if (logToFile == 0) {
	    			/* we log gps data to file */
	    			logToFile = 1;
	    			File tmp = new File(directory + "/usegps/");
	    			tmp.mkdirs();
	    		}
	    	}
	    });
	    
	    /* seek bar for fairness interval */
	    SeekBar seekBar = new SeekBar(this);
	    seekBar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
	    												   ViewGroup.LayoutParams.WRAP_CONTENT));
	    seekBar.setMax(60);
	    seekBar.setProgress(30);
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
		    @Override
		    public void onStopTrackingTouch(SeekBar seekBar) {}
		   
		    @Override
		    public void onStartTrackingTouch(SeekBar seekBar) {}
		   
		    @Override
		    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		    	Toast.makeText( getApplicationContext(), "Value = " + (30 + progress) + " seconds", Toast.LENGTH_SHORT).show();
		    	delta = (30 + progress) * 1000;
		    }
		});
        layout.addView(seekBar);
	    	 
	    /* Start program button */
	    Button button1 = new Button(this);
	    button1.setText("Start");
	    layout.addView(button1);
	    button1.setOnClickListener(new View.OnClickListener() {
	    	public void onClick(View v) {
	    		if (start == 0) {
	    			/* we try to start but we don't have a server defined */
	    			if ((url == null) && (logToFile == 0)) {
	    				Toast.makeText( getApplicationContext(), "Please define a server address", Toast.LENGTH_SHORT).show();
	    			} else {	    		
	    				start = 1;
	    			}
	    		}
	    	}
	    });
	    
	    Button button2 = new Button(this);
	    button2.setText("Exit");
	    layout.addView(button2);
	    button2.setOnClickListener(new View.OnClickListener() {
	    	public void onClick(View v) {
	    		System.exit(0);
	    	}
	    });
	    
	    setContentView(layout);		
		
		/* Use the LocationManager class to obtain GPS locations */
	    LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		LocationListener mlocListener = new MyLocationListener();
		mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
	}
	
	/* method for retrieving body from a http response */
	public static String getResponseBody(final HttpEntity entity) throws IOException {
		if (entity == null)
			throw new IllegalArgumentException("HTTP entity may not be null"); 

		InputStream instream = entity.getContent();
		if (instream == null) 
			return ""; 

		if (entity.getContentLength() > Integer.MAX_VALUE)
			throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");

		String charset = getContentCharSet(entity);
		if (charset == null)
			charset = HTTP.DEFAULT_CONTENT_CHARSET;

		Reader reader = new InputStreamReader(instream, charset);
		StringBuilder buffer = new StringBuilder();
		try {
			char[] tmp = new char[1024];
			int l;
			while ((l = reader.read(tmp)) != -1) {
				buffer.append(tmp, 0, l);
			}
		} finally {
			reader.close();
		}

		return buffer.toString();
	}

	public static String getContentCharSet(final HttpEntity entity) {
		if (entity == null) 
			throw new IllegalArgumentException("HTTP entity may not be null");

		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) 
					charset = param.getValue();
			}
		}

		return charset;
	}

	/* Class My Location Listener */
	public class MyLocationListener implements LocationListener {
		
		Date date = new Date();
		TelephonyManager tm = (TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
		
		String fileName = date.getDay() + "" + date.getMonth() + "" + date.getYear() + ".log";
		File logFile = new File(directory + "/usegps/", fileName);
		long currentTime;
		String deviceId = tm.getDeviceId();
				
		@Override
		public void onLocationChanged(Location loc) {
				
			if (start == 1) {
				double lat = loc.getLatitude();
				double lon = loc.getLongitude();
				
				if (logToFile == 1) {
					/* log gps data to file */
					currentTime = System.currentTimeMillis();
					
					if (currentTime - lastTime >= delta) {
						lastTime = currentTime;
							
						try {
							/* open file in append mode */
							FileWriter fw = new FileWriter(logFile, true);
							BufferedWriter bw = new BufferedWriter(fw); 
							bw.write(lat + " - " + lon + "\n");
							bw.close(); 
						} catch (Exception e) {};
					}
				} else {
					/* send gps data to central server */
					
					//String Text = "My location is:\n" + "Latit: " + lat + "\nLongit: " + lon;
					//Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
					String textToSend;
					
					currentTime = System.currentTimeMillis();
					
					if (currentTime - lastTime >= delta) {
						
						lastTime = currentTime;
						
						textToSend = url + "/" + deviceId + "/" + lat + "/" + lon + "/";
						
						HttpClient client = new DefaultHttpClient();
						HttpGet get = new HttpGet(textToSend);
						HttpResponse resp;
						
						try {
							// ex. http://www.google.com
							Toast.makeText( getApplicationContext(), "Making a request to " + textToSend, Toast.LENGTH_SHORT).show();
							resp = client.execute(get);
							HttpEntity entity = resp.getEntity();
							String res = getResponseBody(entity);
							Toast.makeText( getApplicationContext(), res, Toast.LENGTH_SHORT).show();
						} catch (Exception e) {
							Toast.makeText( getApplicationContext(), "Exception on making a request", Toast.LENGTH_SHORT).show();
						};
					}
				}
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}/* End of Class MyLocationListener */
	
}/* End of UseGps Activity */